package ruc.DolphinDB.read;

import com.xxdb.DBConnection;
import ruc.Consts.constant;
import ruc.DolphinDB.DolphinDB_Common;
import ruc.utils.IOUtils;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

public class DolphinDB_DiffResSet {
    private static final int CLIENT = 15;
    private int bound, port;
    private String IP, tbName;

    private DolphinDB_DiffResSet(String IP, int port, String tbName,int bound) {
        this.IP = IP;
        this.port = port;
        this.tbName = tbName;
        this.bound = bound;
    }

    private String getQuery(int offset, int limit) {
        String format = "select * from %s limit %d, %d";
        return String.format(format, tbName, offset, limit);
    }

    private void DiffResSetRead(int record[]) throws InterruptedException, IOException {
        Random ran = new Random();
        DBConnection con = DolphinDB_Common.getDBConnection(IP, port);
        for(int i = 0; i < record.length; i++) {
            CountDownLatch CDL = new CountDownLatch(CLIENT);
            AtomicLong AL = new AtomicLong(0);
            for(int j = 0; j < CLIENT; j++) {
                int finalI = i;
                new Thread(()->{
                    long startTime = System.nanoTime();
                    try {
                        con.run(getQuery(ran.nextInt(bound), record[finalI]));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    AL.addAndGet((System.nanoTime() - startTime) / constant.Ns2Ms);
                    CDL.countDown();
                }).start();
            }

            CDL.await();
            System.out.printf("[TSBench-D] >>>>> [TDEngine_DiffResSet] record Line : %d, average response time : %d >>>>>\n", record[i], AL.longValue() / CLIENT);
            IOUtils.WriteData(constant.GetWriteFilePath("DolphinDB", "DiffResSet"),
                    new String[]{String.valueOf(System.nanoTime()), String.valueOf(record[i]), String.valueOf(AL.longValue() / CLIENT)});
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        DolphinDB_DiffResSet db = new DolphinDB_DiffResSet(constant.IP, constant.DolphinDB_Port, constant.Concurrent_tbName, constant.bound);
        db.DiffResSetRead(constant.RecordNum);
    }
}
